package com.roncoo.education.course.service.payjs;

import com.roncoo.education.course.service.payjs.util.HttpInvoker;
import com.roncoo.education.course.service.payjs.util.PriceUtil;
import com.roncoo.education.course.service.payjs.util.SignUtil;
import com.roncoo.education.system.common.bean.vo.SysVO;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "payjs")
//@PropertySource("classpath:application.properties")
public class PayJSConfig {

    private String mchid;
    private String key;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getMchid() {
        return mchid;
    }

    public void setMchid(String mchid) {
        this.mchid = mchid;
    }


    /**
     *
     * @param money 元
     * @param body
     * @param sys
     * @return
     */
    public String nativePay(String orderNo, BigDecimal money, String body, SysVO sys){
        if(StringUtils.isEmpty(getKey()) || StringUtils.isEmpty(getMchid())){
            throw new RuntimeException("未找到支付配置,mchid/key");
        }
        String notifyUrl = sys.getNotifyUrl();
        if(StringUtils.isEmpty(notifyUrl)){
            throw new RuntimeException("未找到支付回调配置！");
        }

        //元转换成分
        String moneyFen = PriceUtil.changeY2F(money);

        Map<String,String> map = new HashMap<>();
        map.put("mchid", this.getMchid());
        map.put("total_fee",""+moneyFen);
//        String out_trade_no = "order"+System.currentTimeMillis();
        map.put("out_trade_no",orderNo);
        map.put("body",body);

        map.put("notify_url", notifyUrl);//请注意，，该路径需要payjs服务器可以直接访问，且结果为200。测试地址不行，www.baidu.com也不行
        String md5 = SignUtil.sign(map, this.getKey());
        map.put("sign", md5.toUpperCase());
        map.put("body", map.get("body"));
//        map.put("notify_url", map.get("notify_url"));
        String result = HttpInvoker.readContentFromPost("https://payjs.cn/api/native", map);
        return result;
    }
}
